<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item prop="dictName">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入模型名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dict:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dict:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dict:remove']"
        >删除</el-button>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange" v-table height="0">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template v-slot="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="模型描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="模型名称" align="center" :show-overflow-tooltip="true">
        <template v-slot="scope">
          <router-link :to="'/model/info-apiCollection/index/' + scope.row.id" class="link-type">
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="模型作者" align="center" prop="author"  />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            v-if="scope.row.auditStatus === 1"
            size="mini"
            type="text"
            icon="el-icon-position"
            @click="$message.success('发布申请成功');"
          >发布申请</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="handleApplyList(scope.row)"
              v-if="scope.row.auditStatus === 3"
          >申请列表 <b class="numberDot">{{scope.row.applyNumber}}</b></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body center :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模型分类" prop="modelCategoryId">
          <treeselect
            v-model="form.modelCategoryId"
            :options="menuOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择模型分类"
          />
        </el-form-item>
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item label="模型作者" prop="name">
          <el-input v-model="form.author" placeholder="请输入模型作者" />
        </el-form-item>
        <el-form-item label="模型描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入模型描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="模型图片"
          prop="image"
        >
          <div class="flex align-center justify-start">
            <image-upload
              style="margin-left: 0;"
              v-model="form.imageUrl"
              :limit="1"
            />
          </div>
        </el-form-item>

        <el-form-item
          label="附件"
          prop="attachment"
        >
          <el-upload
            ref="upload"
            :limit="5"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-remove="handleRemove"
            :auto-upload="true"
            :before-upload="beforeUpload"
          >
            <el-button
              slot="trigger"
              size="small"
              type="primary"
            >选取文件</el-button>
            <!-- <el-button
              style="margin-left: 10px;"
              size="small"
              type="success"
              :loading="upload.isUploading"
              @click="submitUpload"
            >上传到服务器</el-button> -->
            <div
              slot="tip"
              class="el-upload__tip"
            >文件大小不超过 20MB</div>
          </el-upload>

        </el-form-item>

        <el-form-item label="操作指南">
          <editor
            v-model="form.richText"
            :min-height="192"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" icon="el-icon-check">确 定</el-button>
        <el-button @click="cancel" icon="el-icon-close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {listBasicInfo,getBasicInfo,delBasicInfo,addBasicInfo,updateBasicInfo,publishApply} from "@/api/model/info"
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listCategory} from "@/api/model/category";
import {listApply} from "@/api/model/apply"
export default {
  name: "basicInfo",
  components: {Treeselect},
  dicts: ['sys_normal_disable'],
  data() {
    return {
      menuOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模型名称不能为空", trigger: "blur" }
        ],

      },
    upload: {
      // 是否禁用上传
      isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
      // 上传的地址 /网关/控制器
      url: process.env.VUE_APP_BASE_API + "/file/upload",
        fileList: [],
    },

    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    getList() {
      this.loading = true;
      listBasicInfo(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.typeList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        description: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.$set(this.form,'richText','<p><strong>评估目标：</strong></p><p><br></p><p><br></p><p><strong>评估依据：</strong></p><p><br></p><p><br></p><p><strong>适用场景：</strong></p><p><br></p><p><br></p><p><strong>操作流程：</strong></p><p><br></p><p><br></p><p><strong>评估结果：</strong></p><p><br></p><p><br></p><p><strong>风险处理原则：</strong></p><p><br></p><p><br></p><p><strong>模型应用注意事项：</strong></p>')
      this.title = "添加模型基本信息";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      // getBasicInfo(id).then(response => {
        this.form = row;
        const annex = this.form['annexUrl'];
        this.upload.fileList = JSON.parse(annex);
        this.open = true;
        this.title = "修改模型基本信息";
      // });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.upload.fileList.length > 0) {
            this.form.annexUrl = JSON.stringify(this.upload.fileList);
          }
          if (this.form.id !== void 0) {
            updateBasicInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBasicInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认？').then(function() {
        return delBasicInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 发布申请  */
    handleApply(row){
      publishApply(row.id).then(res=>{
        if(res.code === 200){
          this.$message.success("发布申请成功");
          this.getList();
        }
      })
    },
    handleApplyList(row){
      this.$tab.openPage(
        "申请列表",
        `apply/${row.id}`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code == 200) {
        const fileInfo = [{ name: file.name, url: response.data.url }];
        this.upload.fileList = [].concat(this.upload.fileList, fileInfo);
        this.$modal.msgSuccess("上传成功");
      }

    },
    handleRemove(file, fileList) {
      if (this.upload.fileList.length > 0) {
        this.upload.fileList = this.upload.fileList.filter(
          (val) => val.name !== file.name
        );
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 20MB!");
        return false;
      }
      return true;
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.menuOptions = [];
        const menu = { id: 0, categoryName: '顶级节点', children: [] };
        menu.children = this.handleTree(response.data, "id","parentId");
        this.menuOptions.push(menu);
      });
    },
  }
};
</script>

<style scoped>
.item {
  margin-top: 10px;
  margin-right: 40px;
}
.numberDot{
  background: #f33;
  font-size: 12px;
  color: #fff;
  text-align: center;
  line-height: 14px;
  border-radius: 50%;
  padding: 0 3px;
  position: relative;
  top: -1px;
}
</style>
